package org.demo.hdfs.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.demo.hdfs.tools.HadoopTools;
import org.demo.hdfs.tools.HttpServletTool;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class HdfsController {

	// 创建目录
	@GetMapping("test1")
	public String test1() throws Exception {
		FileSystem fs = HadoopTools.fileSystem();
		fs.mkdirs(new Path("/1108/daxian/banzhang2"));
		fs.close();
		return "ok";
	}

	// 上传文件
	@GetMapping("test2")
	public String test2() throws Exception {
		FileSystem fs = HadoopTools.fileSystem();
		fs.copyFromLocalFile(new Path("c:/spring.log"), new Path("/1108/daxian/banzhang/spring.log"));
		fs.close();
		return "ok";
	}

	// 下载文件
	@GetMapping("test3")
	public String test3() throws Exception {
		FileSystem fs = HadoopTools.fileSystem();
		fs.copyToLocalFile(false, new Path("/1108/daxian/banzhang/spring.log"), new Path("c:/banhua.txt"), true);
		fs.close();
		return "ok";
	}

	// 删除文件
	@GetMapping("test4")
	public String test4() throws Exception {
		FileSystem fs = HadoopTools.fileSystem();
		fs.delete(new Path("/1108"), true);
		fs.close();
		return "ok";
	}

	// 上传文件
	@PostMapping("test5")
	public String test5(MultipartFile file) throws Exception {
		FileSystem fs = HadoopTools.fileSystem();
		String fileName = file.getOriginalFilename();
		Path newPath = new Path("/1108/daxian/banzhang2/" + fileName);
		FSDataOutputStream outputStream = fs.create(newPath);
		outputStream.write(file.getBytes());
		outputStream.close();
		fs.close();
		return "ok";
	}

	// 下载文件
	@GetMapping("test6")
	public void test6() throws Exception {
		HttpServletResponse response = HttpServletTool.getResponse();
		FileSystem fs = HadoopTools.fileSystem();
		String fileName="需求评估.xlsx";
        fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
		Path srcPath = new Path("/1108/daxian/banzhang2/需求评估.xlsx");
		FSDataInputStream open = fs.open(srcPath);
		InputStream inputStream = new BufferedInputStream(open);
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		byte[] buffer = new byte[inputStream.available()];
		inputStream.read(buffer);
        response.setContentType("application/octet-stream");
        outputStream.write(buffer);
        outputStream.flush();
	}
}
